package cn.tedu.store.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import cn.tedu.store.config.util.HttpUtil;
import cn.tedu.store.config.util.SendPhoneUtil;
import cn.tedu.store.entity.*;
import cn.tedu.store.entity.dto.PageDto;
import cn.tedu.store.mapper.*;
import cn.tedu.store.service.IRepairService;
import cn.tedu.store.service.ex.InsertException;
import cn.tedu.store.temperatureDetection.entity.dto.EmployeeDto;
import cn.tedu.store.util.NumberUtils;
import cn.tedu.store.util.Util;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RepairServiceImpl implements IRepairService {

    //idea 注入bean找不到，File->settings->editon->inspections
    @Autowired
    private RepairMapper repairMapper;

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

    String data1="{\n" +
            "           \"touser\":\"oawgq5tM_jfuTN90_BS_KrOFrZHw\",\n" +
            "           \"template_id\":\"ID-3psAVIqgPAiosphyD1A7MRhVRh3oyWFWJjPeDyck\",\n" +
            "           \"url\":\"http://www.zjsrmyy.com\",  \n" +
            "           \"data\":{\n" +
            "                   \"first\": {\n" +
            "                       \"value\":\"有个维修申请,请查看!\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   },\n" +
            "                   \"keyword1\":{\n" +
            "                       \"value\":\"信息系统软硬件故障\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   },\n" +
            "                   \"keyword2\": {\n" +
            "                       \"value\":\"现在\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   },\n" +
            "                   \"keyword3\": {\n" +
            "                       \"value\":\"申请科室所在地点\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   },\n" +
            "                   \"remark\":{\n" +
            "                       \"value\":\"尽快抢单！\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   }\n" +
            "           }\n" +
            "       }";


    String data2="{\n" +
            "           \"touser\":\"oawgq5tM_jfuTN90_BS_KrOFrZHw\",\n" +
            "           \"template_id\":\"ID-TjZF1czErPsIRhPlmWy73uRb3IGLw9Hjk8xC7D9j-So\",\n" +
            "           \"url\":\"http://www.zjsrmyy.com\",  \n" +
            "           \"data\":{\n" +
            "                   \"first\": {\n" +
            "                       \"value\":\"有个维修申请,请查看!\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   },\n" +
            "                   \"keyword1\":{\n" +
            "                       \"value\":\"信息系统软硬件故障\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   },\n" +
            "                   \"keyword2\": {\n" +
            "                       \"value\":\"现在\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   },\n" +
            "                   \"keyword3\": {\n" +
            "                       \"value\":\"申请科室所在地点\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   },\n" +
            "                   \"keyword4\": {\n" +
            "                       \"value\":\"联系方式\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   },\n" +
            "                   \"remark\":{\n" +
            "                       \"value\":\"尽快抢单！\",\n" +
            "                       \"color\":\"#173177\"\n" +
            "                   }\n" +
            "           }\n" +
            "       }";

    //

//    String data1="{\n" +
//            "           \"touser\":\"oawgq5tM_jfuTN90_BS_KrOFrZHw\",\n" +
//            "           \"template_id\":\"ID-3psAVIqgPAiosphyD1A7MRhVRh3oyWFWJjPeDyck\",\n" +
//            "           \"url\":\"https://www.zjsrmyy.com\",  \n" +
//            "           \"miniprogram\":{\n" +
//            "           \"appid\":\"wxbe061859f1488b2c\",\n" +
//            "           \"pagepath\":\"pages/index/index\"\n" +
//            "           },\n" +
//            "           \"data\":{\n" +
//            "                   \"first\": {\n" +
//            "                       \"value\":\"有个维修申请,请查看!\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword1\":{\n" +
//            "                       \"value\":\"信息系统软硬件故障\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword2\": {\n" +
//            "                       \"value\":\"现在\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword3\": {\n" +
//            "                       \"value\":\"申请科室所在地点\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"remark\":{\n" +
//            "                       \"value\":\"尽快抢单！\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   }\n" +
//            "           }\n" +
//            "       }";
//
//    String data3="{\n" +
//            "           \"touser\":\"oawgq5tM_jfuTN90_BS_KrOFrZHw\",\n" +
//            "           \"template_id\":\"ID-3psAVIqgPAiosphyD1A7MRhVRh3oyWFWJjPeDyck\",\n" +
//            "           \"url\":\"http://www.zjsrmyy.com\",  \n" +
//            "           \"data\":{\n" +
//            "                   \"first\": {\n" +
//            "                       \"value\":\"有个维修申请,请查看!\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword1\":{\n" +
//            "                       \"value\":\"信息系统软硬件故障\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword2\": {\n" +
//            "                       \"value\":\"现在\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword3\": {\n" +
//            "                       \"value\":\"申请科室所在地点\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"remark\":{\n" +
//            "                       \"value\":\"尽快抢单！\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   }\n" +
//            "           }\n" +
//            "       }";
//
//    String data4="{\n" +
//            "           \"touser\":\"oawgq5nvxDKgMjyyGua9qc1bkM2Y\",\n" +
//            "           \"template_id\":\"ID-3psAVIqgPAiosphyD1A7MRhVRh3oyWFWJjPeDyck\",\n" +
//            "           \"url\":\"http://www.zjsrmyy.com\",  \n" +
//            "           \"data\":{\n" +
//            "                   \"first\": {\n" +
//            "                       \"value\":\"有个维修申请,请查看!\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword1\":{\n" +
//            "                       \"value\":\"信息系统软硬件故障\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword2\": {\n" +
//            "                       \"value\":\"现在\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword3\": {\n" +
//            "                       \"value\":\"申请科室所在地点\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"remark\":{\n" +
//            "                       \"value\":\"尽快抢单！\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   }\n" +
//            "           }\n" +
//            "       }";
//
//    String data5="{\n" +
//            "           \"touser\":\"oawgq5nG_hCB2Uk7FeDR6Vkf0Xi4\",\n" +
//            "           \"template_id\":\"ID-3psAVIqgPAiosphyD1A7MRhVRh3oyWFWJjPeDyck\",\n" +
//            "           \"url\":\"http://www.zjsrmyy.com\",  \n" +
//            "           \"data\":{\n" +
//            "                   \"first\": {\n" +
//            "                       \"value\":\"有个维修申请,请查看!\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword1\":{\n" +
//            "                       \"value\":\"信息系统软硬件故障\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword2\": {\n" +
//            "                       \"value\":\"现在\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword3\": {\n" +
//            "                       \"value\":\"申请科室所在地点\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"remark\":{\n" +
//            "                       \"value\":\"尽快抢单！\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   }\n" +
//            "           }\n" +
//            "       }";
//
//    String data6="{\n" +
//            "           \"touser\":\"oawgq5vZWDnSkqCMJ9GJdelm9Vj8\",\n" +
//            "           \"template_id\":\"ID-3psAVIqgPAiosphyD1A7MRhVRh3oyWFWJjPeDyck\",\n" +
//            "           \"url\":\"http://www.zjsrmyy.com\",  \n" +
//            "           \"data\":{\n" +
//            "                   \"first\": {\n" +
//            "                       \"value\":\"有个维修申请,请查看!\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword1\":{\n" +
//            "                       \"value\":\"信息系统软硬件故障\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword2\": {\n" +
//            "                       \"value\":\"现在\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword3\": {\n" +
//            "                       \"value\":\"申请科室所在地点\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"remark\":{\n" +
//            "                       \"value\":\"尽快抢单！\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   }\n" +
//            "           }\n" +
//            "       }";
//
//    String data7="{\n" +
//            "           \"touser\":\"oawgq5vl0RswNgJ3PREV6MTQdUMQ\",\n" +
//            "           \"template_id\":\"ID-3psAVIqgPAiosphyD1A7MRhVRh3oyWFWJjPeDyck\",\n" +
//            "           \"url\":\"http://www.zjsrmyy.com\",  \n" +
//            "           \"data\":{\n" +
//            "                   \"first\": {\n" +
//            "                       \"value\":\"有个维修申请,请查看!\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword1\":{\n" +
//            "                       \"value\":\"信息系统软硬件故障\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword2\": {\n" +
//            "                       \"value\":\"现在\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"keyword3\": {\n" +
//            "                       \"value\":\"申请科室所在地点\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   },\n" +
//            "                   \"remark\":{\n" +
//            "                       \"value\":\"尽快抢单！\",\n" +
//            "                       \"color\":\"#173177\"\n" +
//            "                   }\n" +
//            "           }\n" +
//            "       }";




    String AllOpenId[]={"oawgq5tM_jfuTN90_BS_KrOFrZHw"
            ,"oawgq5lULhXxL865bUoksVWE1t6U",
            "oawgq5sYx3w4ochQu4XzkLfJwds8",
            "oawgq5nvxDKgMjyyGua9qc1bkM2Y",
            "oawgq5nG_hCB2Uk7FeDR6Vkf0Xi4",
            "oawgq5vZWDnSkqCMJ9GJdelm9Vj8",
            "oawgq5vl0RswNgJ3PREV6MTQdUMQ"
    };


    String testOpenId[]={
            "oawgq5h8aFvLV6xJqRKAigrTjH9M",
            "oawgq5lULhXxL865bUoksVWE1t6U",
            "oawgq5ismmXlYhSQmUcUoIzJpOmI",
            "oawgq5sYx3w4ochQu4XzkLfJwds8",
            "oawgq5nG_hCB2Uk7FeDR6Vkf0Xi4",
            "oawgq5vZWDnSkqCMJ9GJdelm9Vj8",
            "oawgq5tM_jfuTN90_BS_KrOFrZHw"
    };
    private Repair repair;


    @Resource
    StringRedisTemplate stringRedisTemplate;


    @Override
    public String repairApply(Repair repair) {
        this.repair = repair;
        if (!Objects.isNull(repair.getRepairLeadership())){
            if (repair.getRepairLeadership().length()>0){
                repair.setRepairLeadership(repair.getRepairLeadership().substring(0,6));
            }
        }


//        String maxId = repairMapper.repairSelectMaxId();

//        if (StrUtil.isNotBlank(maxId)) {
//            String day_base = maxId.substring(0, 8);
//            String currDate = DateUtil.format(DateUtil.date(), "yyyyMMdd");
//            if (day_base.equals(currDate)){
//                String sequese_base = StrUtil.subSuf(maxId,8);
//                Integer integer = Integer.valueOf(sequese_base)+1;
//                String id=String.format("%4d", integer).replace(" ", "0");
//                maxId=day_base+id;
//            }else {
//                maxId = DateUtil.format(DateUtil.date(), "yyyyMMdd") + "0001";
//            }
//        } else {
//            maxId = DateUtil.format(DateUtil.date(), "yyyyMMdd") + "0001";
//        }
        System.out.println(repair);

        repair.setRepairApplyId(String.valueOf(System.currentTimeMillis()));
        repair.setState("1");
        System.out.println("执行");
        if (!Objects.isNull(repair.getRepairOperator())){

            if (repair.getRepairOperator().equals("")||repair.getRepairOperator().equals(null)){
                repair.setRepairState("1");
                repair.setRepairOperator(null);
            }else {
                repair.setRepairState("2");

            }

        }

        repair.setRepairApplyDate(new Date());
//        Date date = new Date();
//        Calendar cal = Calendar.getInstance();
//        if (!Objects.isNull(repair.getRepairTime())){
//            if (repair.getRepairTime().equals("0")){
//                cal.add(Calendar.MINUTE,30);
//            }else {
//                cal.add(Calendar.DATE,repair.getRepairTime());
//            }
//        }else {
//            cal.add(Calendar.MINUTE,30);
//
//        }


//        repair.setRepairFinishedDate(cal.getTime());

        System.out.println(repair);
        //Integer row = repairMapper.insert(repair);
        Integer row = repairMapper.insert1(repair);
//        Department dp=new Department();
//        dp.setDeptName("1501");
        //redis任务队列
//        stringRedisTemplate.opsForList().leftPush("weixiu", JSONUtil.toJsonPrettyStr(repair));


//        Repair repair1 = repairMapper.selectMyRepairOrderById(repair.getRepairApplyId(),);
        String repairApplyOperator = repair.getRepairApplyOperator();
        String repairApplyType = repair.getRepairApplyType();
        String repairApplyDetail = repair.getRepairApplyDetail();
        String repairApplyDept = repair.getRepairApplyDept();
        String repairApplyPhone = repair.getRepairApplyPhone();
        if (repair.getRepairState().equals("2")){
            //指派
            String status = "1";
            repairMapper.addAssign(repair.getRepairApplyId(),repairApplyOperator,new Date(),repair.getRepairOperator(),status);

        }

        //通过申请电话获取申请人
        List<Employee> employees = repairMapper.selectEmployee(repairApplyPhone);
        String employeeName = employees.get(0).getEmployeeName();
        //获取申请人科室
        List<Department> departments = repairMapper.selectDepartById(employees.get(0).getEmployeeDept());

        String deptName = departments.get(0).getDeptName();


        if (row != 1) {
            throw new InsertException("插入数据失败");
        }else {
            if (!Objects.isNull(repair.getRepairOperator())){

                if (repair.getRepairOperator().length()>5){
                    //智能呼叫
                    EmployeeDto byEmplCode = employeeMapper.getByEmplCode(repair.getRepairOperator());
                    sendPhone3(repairApplyDetail,repairApplyPhone,repairApplyType,deptName,employeeName,byEmplCode);
                }else {

                    sendPhone(repair.getRepairApplyId(),repairApplyPhone,repairApplyType,deptName,employeeName);

                }

            }else {
                //智能呼叫
                sendPhone(repair.getRepairApplyId(),repairApplyPhone,repairApplyType,deptName,employeeName);

            }




            String url_phone="http://192.168.1.110:8081";
//            //短息发送
            String param_phone="SmsServer.ashx?id=1&" +
                    "phone=18871742296&" +
                    "phone=18608608556&" +
                    "phone=13477837799&" +
                    "phone=13872497873&" +
                    "phone=15072562385&" +
                    "phone=15872485525&" +
                    "content=有新的维修申请可以接单:"+employeeName+"||"+deptName+"||"+repairApplyType+"||"+repairApplyDetail+"||"+repairApplyPhone;
            sendGet(url_phone,param_phone);
            //公众号推送
            for(int i=0;i<AllOpenId.length;i++){
                String openId=AllOpenId[i];
                //JSON格式的字符串替换
                JSONObject jsonObj = JSONObject.fromObject(data1);
                String ss = jsonObj.getString("touser");

                data1 = data1.replace(ss,openId);

                data1 = data1.replace("申请科室所在地点",deptName);
                data1 =data1.replace("信息系统软硬件故障",repairApplyDetail);
                SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy月MM号dd日HH时mm分ss秒");
                data1 = data1.replace("现在",simpleDateFormat3.format(new Date()));

                //公众号推送消息
                sendTemplateMessage();
              }


            }
return   repair.getRepairApplyId();
        }



    private void sendPhone3(String repairApplyId, String repairApplyPhone, String repairApplyType, String deptName, String employeeName, EmployeeDto byEmplCode) {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取token
        com.alibaba.fastjson.JSONObject body = new com.alibaba.fastjson.JSONObject();
        body.put("username","13477857785");
        body.put("apiKey","6a$@m?*j261@l!f");
        body.put("transactionId","10086202211141249");
        Map s =   (Map)com.alibaba.fastjson.JSONObject.parseObject(HttpUtil.doPost(HttpUtil.url + HttpUtil.token, body)).get("bean");
        //请求头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", (String) s.get("token"));
        String format = simpleDateFormat.format(date);
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, 5)));
        //添加任务
        Tenant tenant = new Tenant();
        tenant.setTransactionId(1085+format+code);
        tenant.setTenantId("2023040310553681671");
        tenant.setProcessId(2023041711400105637L);
        tenant.setProcessName("指定派单");
        tenant.setTaskName("指定派单"+simpleDateFormat1.format(new Date()));
        tenant.setConcurrentNum(1);
        tenant.setOutCallNums("07174516097");
        tenant.setIsAllday(1);
        tenant.setForever(0);
        tenant.setRecallNum(2);
        tenant.setRecallTime(1);
        tenant.setPlanStime("2023-01-11");
        tenant.setPlanEtime("2025-01-11");
        tenant.setStartTime1("08:00:00");
        tenant.setEndTime1("12:00:00");
        tenant.setStartTime2("14:00:00");
        tenant.setEndTime2("17:30:00");
        //添加人员信息
        List<CalledInfo> calledInfos = new ArrayList<>();




            CalledInfo calledInfo = new CalledInfo();
            calledInfo.setRemark(byEmplCode.getRemark());
            calledInfo.setPhone(byEmplCode.getRemark());
            calledInfo.setContacts(byEmplCode.getEmplName());

            ArrayList<Variable> variables = new ArrayList<>();
            Variable v1 = new Variable();
            v1.setKey("repairApplyId");
            v1.setValue(repairApplyId);

            variables.add(v1);

            calledInfo.setVariable(variables);
            calledInfos.add(calledInfo);

        tenant.setCalledInfo(calledInfos);
        HttpUtil.doPostJson(HttpUtil.url+HttpUtil.Task,headers, com.alibaba.fastjson.JSONObject.toJSONString(tenant));




    }


    private void sendPhone(String repairApplyDetail,String repairApplyPhone,String repairApplyType,String deptName,String employeeName) {
        String c =repairApplyType;
        if (!StringUtils.isBlank(repairApplyDetail)){
             c+=repairApplyDetail;
            }
        ArrayList<CalledInfo> calledInfos = new ArrayList<>();
        List<EmployeeDto> x = employeeMapper.findX();
                x.stream().forEach(ac->{
                DutyTable z = repairMapper.getZ(ac.getEmplCode());
                if (!Objects.isNull(z)){
                    if (!Objects.isNull(z.getBzmc())){
                        ac.setZb(z.getBzmc());
                    }
                }
        });
                List<EmployeeDto> collect = x.stream().filter(e -> e.getZb().equals("值") || e.getZb().equals("白")).collect(Collectors.toList());
        System.out.println(collect);
        for (EmployeeDto employeeDto : collect) {
            CalledInfo calledInfo = new CalledInfo();
            ArrayList<Variable> variables = new ArrayList<>();
            calledInfo.setRemark(employeeDto.getRemark());
            calledInfo.setPhone(employeeDto.getRemark());
            calledInfo.setContacts(employeeDto.getEmplName());
            Variable variable = new Variable();
            variable.setKey("general");
            variable.setValue("你好,有新的维修申请可以接单,申请人"+employeeName+"申请科室"+deptName+"申请详细"+c);
            variables.add(variable);
            calledInfo.setVariable(variables);
            calledInfos.add(calledInfo);
        }
        SendPhoneUtil.sendPhone(calledInfos);
    }

    //微信公众号消息推送
    public void sendTemplateMessage() {
        String url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        url=url.replace("ACCESS_TOKEN",WxService.getAccessToken());
        String result=Util.post(url, data1);
        System.out.println(result);

    }

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "/" + param;
//            URL realUrl = new URL(urlNameString);

            URL realUrl = new URL(urlNameString);
//            URL realUrl = (URL) new DocFlavor.URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {

            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }


    @Override
    public List<Repair> repairSelect(String phone, String deptId) {

        return repairMapper.repairSelect(phone, deptId);
    }

    @Override
    public String repairSelectMaxId() {
        return null;
    }

    @Override
    public List<Employee> selectEmployee(String phone) {
        return repairMapper.selectEmployee(phone);
    }
    @Override
    public List<Department> selectDepartment() {
        return repairMapper.selectDepartment();
    }

    @Override
    public List<Repair> selectRepairOrder(List<Integer> repairState) {

        return repairMapper.selectRepairOrder(repairState);
    }

    @Override
    public void applyDate(RepariOrder repairOrder) {
        Date date = repairMapper.applyDate(repairOrder);
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String s = sdf.format(date);
        repairOrder.setRepairApplyDate(s);
    }

    @Override
    public Integer updateByRepairapplyid(String  repariOrderId,String repairOperator,Date repairAcceptDate) {
        Repair repair = selectMyRepairOrderById(repariOrderId,"1");
        Integer state;
        repairAcceptDate=new Date();
        if (repair!=null&&repair.getRepairApplyId().equals(repariOrderId)){
            repairMapper.updateByRepairapplyid(repariOrderId,repairOperator,repairAcceptDate);
            state=1;
        }else {
            state=-1;
        }
        return state;
    }

    @Override
    public Repair selectMyRepairOrderById(String repairApplyId,String repairState) {
        Repair repair = repairMapper.selectMyRepairOrderById(repairApplyId, repairState);
        EmployeeDto byEmplCode = employeeMapper.getByEmplCode(repair.getRepairApplyOperator());
        repair.setRepairApplyOperator(byEmplCode.getEmplName());
        ComDepartment byDeptCode = employeeMapper.getByDeptCode(repair.getRepairApplyDept());
        repair.setRepairApplyDept(byDeptCode.getDeptEname());

        List<DutyTable> dutyTables = repairMapper.selectXxkPaiban2();


        return repair;
    }

    @Override
    public Integer cancelRepairOrder(String repariOrderId,Date cancelDate) {
        Repair repair = selectMyRepairOrderById(repariOrderId,"1");
        Integer state;
        cancelDate=new Date();
        if (repair!=null&&repair.getRepairApplyId().equals(repariOrderId)){
            repairMapper.cancelRepairOrder(repariOrderId,cancelDate);
            state=1;
        }else {
            state=-1;
        }
        return state;
    }

    @Override
    public List<RepariOrder> selectAllRepairOrder(String repairApplyOperator,String stateOne,String stateTwo,String repairStateOne,String repairStateTwo) {

        List<RepariOrder> repariOrders = repairMapper.selectAllRepairOrder(repairApplyOperator, stateOne, stateTwo, repairStateOne, repairStateTwo);
            repariOrders.stream().forEach(
                    s->{
                        if (!StringUtils.isBlank(s.getRepairOperator())){
                            EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s.getRepairOperator());
                            s.setRepairPhone(byEmplCode.getRemark());

                            s.setRepairOperator(byEmplCode.getEmplName());
                        }
                        TImage tImage = repairMapper.selcetTImage(s.getRepairApplyId());




                        if (Objects.isNull(tImage)){

                            }else {

                            FileInputStream stream = null;
                            try {
                                stream = new FileInputStream(tImage.getCodeUrl());
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }

                            String image  = Base64.encode(stream);
                            s.setImage("data:image/jpg;base64,"+image);
                            }

                        if (StringUtils.isEmpty(s.getRepairLeadership())){

                        }else {

                            EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s.getRepairLeadership());
                            s.setRepairLeadership(byEmplCode.getEmplName());

                            ComDepartment byDeptCode = employeeMapper.getByDeptCode(s.getRepairLeadershipDept());
                            if (!Objects.isNull(byDeptCode)){
                                s.setRepairLeadershipDept(byDeptCode.getDeptName().toString());
                            }

                        }
//                    //处理完成情况
//                        if (s.getRepairState().equals("3")){
//                            if (!StringUtils.isBlank(s.getRepairApplyEndDate().toString())&&!StringUtils.isBlank(s.getRepairEndDate().toString())){
//                                if (s.getRepairApplyEndDate().getTime()>s.getRepairEndDate().getTime()){
//                                    s.setWc("已完成");
//                                }else {
//                                    s.setWc("超时完成");
//                                }
//
//                            }else if (!StringUtils.isBlank(s.getRepairFinishedDate().toString())&&!StringUtils.isBlank(s.getRepairEndDate().toString())){
//                                if (s.getRepairFinishedDate().getTime()>s.getRepairEndDate().getTime()){
//                                    s.setWc("已完成");
//                                }else {
//                                    s.setWc("超时完成");
//                                }
//                            }
//
//
//                        }else {
//                            s.setWc("未完成");
//                        }


                    }
            );



        return repariOrders;

       // return repairMapper.selectAllRepairOrder(repairApplyOperator,stateOne,stateTwo,repairStateOne,repairStateTwo);
    }
    @Override
    public List<RepariOrder> selectAllRepairOrder3(String repairApplyOperator,String stateOne,String stateTwo,String repairStateOne,String repairStateTwo) {
        List<RepariOrder> repariOrders = repairMapper.selectAllRepairOrder8(repairApplyOperator, stateOne, stateTwo, repairStateOne, repairStateTwo);
        repariOrders.stream().forEach(
                s->{
                    TImage tImage = repairMapper.selcetTImage(s.getRepairApplyId());
                    if (Objects.isNull(tImage)){

                    }else {

                        FileInputStream stream = null;
                        try {
                            stream = new FileInputStream(tImage.getCodeUrl());
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }

                        String image  = Base64.encode(stream);
                        s.setImage("data:image/jpg;base64,"+image);
                    }
                    if (StringUtils.isEmpty(s.getRepairLeadership())){

                    }else {

                        EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s.getRepairLeadership());
                        s.setRepairLeadership(byEmplCode.getEmplName());

                        ComDepartment byDeptCode = employeeMapper.getByDeptCode(s.getRepairLeadershipDept());
                        s.setRepairLeadershipDept(byDeptCode.getDeptName().toString());
                    }




                }
        );


        return repariOrders;

        // return repairMapper.selectAllRepairOrder(repairApplyOperator,stateOne,stateTwo,repairStateOne,repairStateTwo);
    }

    @Override
    public void reminders(Repair repair1) {
        //催单
        repairMapper.updateRepairApplyStateByRepair(repair1);
        EmployeeDto byEmplCode = employeeMapper.getByEmplCode(repair1.getRepairOperator());
        //通过申请电话获取申请人
        List<Employee> employees = repairMapper.selectEmployee(repair1.getRepairApplyPhone());
        String employeeName = employees.get(0).getEmployeeName();
        //获取申请人科室
        List<Department> departments = repairMapper.selectDepartById(repair.getRepairApplyDept());
        String deptName = departments.get(0).getDeptName();
        String url_phone="http://192.168.1.110:8081";
//            //短息发送
        String param_phone="SmsServer.ashx?id=1&" +
               "phone=18871742296&" +
                "phone=18608608556&" +
                "phone=13477837799&" +
                "phone=13872497873&" +
                "phone=15072562385&" +
                "phone=15872485525&" +
                "phone=18064244115&" +

                "content=用户:您好！"+deptName+"||"+employeeName+"||"+repair1.getRepairApplyType()+"||"+repair1.getRepairApplyDetail()+"||"+repair1.getRepairApplyId()+"维修订单已进行催单请尽快完成！";
        sendGet(url_phone,param_phone);

    }

    @Override
    public void updateRepairStateByRepairApplyId(String repairApplyId, String repairState, Date date) {
        repairMapper.updateRepairStateByRepairApplyId(repairApplyId,repairState,date);
    }

    @Override
    public void updateComplaintsByRepairapplyid(String repairApplyId, String message) {
        repairMapper.updateComplaintsByRepairapplyid(repairApplyId,message);
    }

    @Override
    public EmployeeDto getbyEmplCode(String emplCode) {
        EmployeeDto byEmplCode = employeeMapper.getByEmplCode(emplCode);

        return byEmplCode;
    }

    @Override
    public Object selectEm() {
        //
        List<EmployeeDto> c = employeeMapper.findX();
        return c;
    }

    @Override
    public String getdept(String repairLeadership) {

        EmployeeDto byEmplCode = employeeMapper.getByEmplCode(repairLeadership.substring(0, 6));
        return byEmplCode.getDeptCode();
    }

    @Override
    public Object selectXxkPaiban1() {
        return repairMapper.selectXxkPaiban5();
    }

    @Override
    public void updataEndTime(String repairApplyId, Date endTime) {
        repairMapper.updateTime(repairApplyId,endTime);
    }
    @Value("${recording.upload.url}")
    private String uploadRecordingFilePath;
    @Override
    public void uploadRecording( MultipartFile file, String repairApplyId, String repairNum,String emplCode) throws IOException {
        if (file.getSize()<=0){
            return;
        }else {


            String originalFilename = file.getOriginalFilename();
//        // 获取原始文件名的后缀
//        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 创建一个目录对象
            File dir = new File(uploadRecordingFilePath);
            // 判断当前目录是否存在
            if (!dir.exists()) {
                // 目录不存在，需要创建
                dir.mkdirs();
            }
            String fileName = repairApplyId+ UUID.randomUUID()+file.getName()+originalFilename;
            Repair repair = repairMapper.selectMyRepair(repairApplyId);

            Recording recording = new Recording();
            recording.setTDate(new Date());
            recording.setRepairApplyId(repairApplyId);
          recording.setRepairRecording(uploadRecordingFilePath+"/"+fileName);
            recording.setRepairNum(repairNum);
            recording.setEmplCode(repairApplyId);
            repairMapper.upLaodRecording(recording);
            try {
                // file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会被删除
                // basePath 是指定的保存路径，我们在上面声明了一个属性，属性值从yml配置文件读取，以便修改
                // 这里可能会有IO异常，我们需要把它抛出去
                file.transferTo(new File(uploadRecordingFilePath + fileName));

            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }

    @Override
    public Recording getRecording(String repairApplyId) {
        Recording recording = repairMapper.getRecording(repairApplyId);
        if (Objects.isNull(recording)){
            return null;
        }else {
            return   recording;
        }

    }

    @Override
    public void upadtaEndTime2(String repairApplyId, Date parse) {
        repairMapper.upadtaEndTime2(repairApplyId,parse);
    }

    @Override
    @Transactional
    public void transfer(String repairApplyId, String emplCode) {


        EmployeeDto byEmplCode = employeeMapper.getByEmplCode(emplCode);
//        ComDepartment byDeptCode = employeeMapper.getByDeptCode(repair.getRepairApplyDept());
        Repair repair = repairMapper.selectMyRepair(repairApplyId);
        if (emplCode.equals(repair.getRepairOperator())){
            throw new RuntimeException("不能转派给自己");
        }

        Transfer transfer = new Transfer();
        transfer.setRepairApplyId(repairApplyId);
        transfer.setRepairTransferDate(new Date());
        transfer.setRepairOperator(repair.getRepairOperator());
        transfer.setRepairTransOperator(emplCode);
        repairMapper.updateOperator(repairApplyId,emplCode);
        repairMapper.insertTransfer(transfer);
        repairMapper.addAssign(repairApplyId,repair.getRepairOperator(),new Date(),emplCode,"3");
        ComDepartment byDeptCode = employeeMapper.getByDeptCode(repair.getRepairApplyDept());
        String url_phone="http://192.168.1.110:8081";
//            //短息发送
        String param_phone="SmsServer.ashx?id=1&phone=" +
               byEmplCode.getRemark() +

                "&content=用户:您好！"+byDeptCode.getDeptName()+"||"+byEmplCode.getEmplName()+"||"+repair.getRepairApplyType()+"||"+repair.getRepairApplyDetail()+"||"+repair.getRepairApplyId()+"维修订单已进行催单请尽快完成！";
        sendGet(url_phone,param_phone);
    }

    @Override
    public List<Transfer> secletAllTransfer() {
        List<Transfer> all = repairMapper.getAll();
        all.stream().forEach(s->{
            if (!StringUtils.isBlank(s.getRepairOperator())){
                EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s.getRepairOperator());
            s.setRepairOperator(byEmplCode.getEmplName());
            }
            if (!StringUtils.isBlank(s.getRepairTransOperator())){
                EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s.getRepairTransOperator());
                s.setRepairTransOperator(byEmplCode.getEmplName());
            }
        });

        return all;
    }

    @Override
    public List<Repair> allOutcome() {
        List<Repair> repairs = repairMapper.all();
        repairs.stream().forEach(s->{
            if (s.getRepairState().equals("3")){
                if (!Objects.isNull(s.getRepairApplyEndDate()) && !Objects.isNull(s.getRepairEndDate())){
                    if (s.getRepairApplyEndDate().getTime()>s.getRepairEndDate().getTime()){
                        s.setRepairState("完成");
                    }else {
                        s.setRepairState("超时完成");
                    }
                }else if (!Objects.isNull(s.getRepairFinishedDate())&&!Objects.isNull(s.getRepairEndDate())){
                    if (s.getRepairFinishedDate().getTime()>s.getRepairEndDate().getTime()){
                        s.setRepairState("完成");
                    }else {
                        s.setRepairState("超时完成");
                    }
                }


            }else {
                s.setRepairState("未完成");
            }
            if (!StringUtils.isEmpty(s.getRepairApplyDept())){
                ComDepartment byDeptCode = employeeMapper.getByDeptCode(s.getRepairApplyDept());
                if (Objects.isNull(byDeptCode)){

                }else{
                    s.setRepairApplyDept((String) byDeptCode.getDeptName());
                }

            }
            if (!StringUtils.isEmpty(s.getRepairOperator())){
                EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s.getRepairOperator());
                if (Objects.isNull(byEmplCode)){

                }else{
                    s.setRepairOperator(byEmplCode.getEmplName());
                }

            }
        });
        return repairs;
    }

    @Override
    public List<RepariOrder> deptAllRepair( String stateOne, String stateTwo, String repairStateOne, String repairStateTwo,String employeeDept) {

        List<RepariOrder> repariOrders = repairMapper.selectDept(employeeDept, stateOne, stateTwo, repairStateOne, repairStateTwo);

        repariOrders.stream().forEach(
                s->{
            log.info("对象{}",JSONObject.fromObject(s));
                    if (!StringUtils.isBlank(s.getRepairOperator())){
                        EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s.getRepairOperator());
                        s.setRepairPhone(byEmplCode.getRemark());

                        s.setRepairOperator(byEmplCode.getEmplName());
                    }
                    TImage tImage = repairMapper.selcetTImage(s.getRepairApplyId());

//
//                    if (Objects.isNull(tImage)){
//
//                    }else {
//
//                        FileInputStream stream = null;
//                        try {
//                            stream = new FileInputStream(tImage.getCodeUrl());
//                        } catch (FileNotFoundException e) {
//                            e.printStackTrace();
//                        }
//
//                        String image  = Base64.encode(stream);
//                        s.setImage("data:image/jpg;base64,"+image);
//                    }

                    if (StringUtils.isEmpty(s.getRepairLeadership())){

                    }else {

                        EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s.getRepairLeadership());
                        s.setRepairLeadership(byEmplCode.getEmplName());

                        ComDepartment byDeptCode = employeeMapper.getByDeptCode(s.getRepairLeadershipDept());
                        s.setRepairLeadershipDept(byDeptCode.getDeptName().toString());
                    }


                }
        );



        return repariOrders;

    }

    //获取未完成任务进行提醒
    @Override
    public void send() {
        //查询订单未2
          List<Repair> repairs =repairMapper.selectTimeoutOrders("2");
          if (Objects.isNull(repairs)){
             return;
          }else {

          //获取获取订单
         List<Repair> RepairTimeout = new ArrayList<Repair>();

        for (Repair s : repairs) {

            if (!Objects.isNull(s.getRepairApplyEndDate())) {
                if (s.getRepairApplyEndDate().getTime() < new Date().getTime()) {
                    RepairTimeout.add(s);
                }

            } else if (!Objects.isNull(s.getRepairFinishedDate())) {
                if (s.getRepairFinishedDate().getTime() < new Date().getTime()) {
                    RepairTimeout.add(s);
                }

            } else {

            }
        }

       RepairTimeout.stream().forEach(s->{
            try {
                java.lang.Thread.sleep(60000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
          if (Objects.isNull(s.getRepairRemind())) {

                  EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s.getRepairOperator());

                  String url_phone = "http://192.168.1.110:8081";
//            //短息发送
                  String param_phone = "SmsServer.ashx?id=1&phone=" +
                          byEmplCode.getRemark() + "&phone=18608608556&" +

                          "&content=用户:你好!订单号" + s.getRepairApplyId() + "已超时请尽快完成！申请人" + byEmplCode.getEmplName()
                          + "申请类型:" + s.getRepairApplyType() + "申请详情:" + s.getRepairApplyDetail() + "申请人电话:" + s.getRepairApplyPhone();
                  sendGet(url_phone, param_phone);
                Date date = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //获取token
                com.alibaba.fastjson.JSONObject body = new com.alibaba.fastjson.JSONObject();
                body.put("username","13477857785");
                body.put("apiKey","6a$@m?*j261@l!f");
                body.put("transactionId","10086202211141249");
                Map l =   (Map)com.alibaba.fastjson.JSONObject.parseObject(HttpUtil.doPost(HttpUtil.url + HttpUtil.token, body)).get("bean");

                //请求头
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", (String) l.get("token"));
                String format = simpleDateFormat.format(date);
                String code = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, 5)));
                //添加任务
                Tenant tenant = new Tenant();
                tenant.setTransactionId(1085+format+code);
                tenant.setTenantId("2023040310553681671");
                tenant.setProcessId(2023040415132105486L);
                tenant.setProcessName("维修超时提醒");
                tenant.setTaskName("维修超时提醒"+simpleDateFormat1.format(new Date()));
                tenant.setConcurrentNum(1);
                tenant.setOutCallNums("07174516097");
                tenant.setIsAllday(1);
                tenant.setForever(1);
                tenant.setRecallNum(2);
                tenant.setRecallTime(1);
                tenant.setPlanStime("2023-01-11");
                tenant.setPlanEtime("2025-01-11");
                tenant.setStartTime1("08:00:00");
                tenant.setEndTime1("12:00:00");
                tenant.setStartTime2("14:00:00");
                tenant.setEndTime2("17:30:00");
                //添加人员信息
                List<CalledInfo> calledInfos = new ArrayList<>();
                CalledInfo calledInfo = new CalledInfo();
                calledInfo.setPhone(byEmplCode.getRemark());
                ArrayList<Variable> variables = new ArrayList<>();
                Variable variable = new Variable();
                variable.setKey("repairApplyPhone");
                variable.setValue(s.getRepairApplyPhone());
                Variable variable1 = new Variable();
                variable1.setKey("repairApplyDetail");
                variable1.setValue(s.getRepairApplyDetail());
                Variable variable2 = new Variable();
                variable2.setKey("repairApplyType");
                variable2.setValue(s.getRepairApplyType());
                Variable variable3 = new Variable();
                variable3.setKey("deptName");
                variable3.setValue(s.getRepairApplyDept());
                Variable variable4 = new Variable();
                variable4.setKey("employeeName");
                variable4.setValue(s.getRepairName());
                Variable variable5 = new Variable();
                variable5.setKey("repairapplyid");
                variable5.setValue(s.getRepairApplyId());
                tenant.setCalledInfo(calledInfos);
                tenant.setCreateBy("2023040310553681671");
                tenant.setCreateUser("枝江市人民医院");
              String s1 = com.alibaba.fastjson.JSONObject.toJSONString(tenant);
              HttpUtil.doPostJson(HttpUtil.url + HttpUtil.Task, headers, s1);
                  repairMapper.updateRepairRemind(s.getRepairApplyId(), "1");

  }else {

              System.out.println("111");
          }
       });}

    }

    @Override
    public List<RepariOrder> relevantPersonnel(String emplCode) {

        List<RepariOrder> relevantPersonnel = repairMapper.getRelevantPersonnel(emplCode);
        relevantPersonnel.stream().forEach(s->{
            EmployeeDto leadership = employeeMapper.getByEmplCode(s.getRepairLeadership());
            s.setRepairLeadership(leadership.getEmplName());

            ComDepartment leadershipDept = employeeMapper.getByDeptCode(s.getRepairLeadershipDept());
            s.setRepairLeadershipDept(leadershipDept.getDeptName().toString());
            if (!Objects.isNull(s.getRepairOperator())){
                s.setRepairOperator(employeeMapper.getByEmplCode(s.getRepairOperator()).getEmplName());
            }


        });

        return relevantPersonnel;
    }

    @Override
    public void updateFinishedDate(String repairApplyId, int time) {
        Repair repair = repairMapper.selectMyRepair(repairApplyId);
        if (Objects.isNull(repair.getRepairFinishedDate())){
            //设置创建时间
            Date creatTime = new Date();

            //设置生效时间为一小时后
            Calendar cal = Calendar.getInstance();
            cal.setTime(creatTime);
            cal.add(Calendar.HOUR, time);// 24小时制
            Date effectivetime = cal.getTime();
            repairMapper.updateTime(repairApplyId,effectivetime);

        }else {
            Date repairFinishedDate = repair.getRepairFinishedDate();
            Calendar cal = Calendar.getInstance();
            cal.setTime(repairFinishedDate);
            cal.add(Calendar.HOUR,time);
            Date time1 = cal.getTime();
            repairMapper.updateTime(repairApplyId,time1);
        }
    }

    @Override
    public void updateApplyEndDate(String repairApplyId, int time) {
        Repair repair = repairMapper.selectMyRepair(repairApplyId);
        if (Objects.isNull(repair.getRepairApplyEndDate())){
            //设置创建时间
            Date creatTime = new Date();

            //设置生效时间为一小时后
            Calendar cal = Calendar.getInstance();
            cal.setTime(creatTime);
            cal.add(Calendar.HOUR, time);// 24小时制
            Date effectivetime = cal.getTime();
            repairMapper.upadtaEndTime2(repairApplyId,effectivetime);

        }else {
            Date repairFinishedDate = repair.getRepairApplyEndDate();

            Calendar cal = Calendar.getInstance();
            cal.setTime(repairFinishedDate);
            cal.add(Calendar.HOUR,time);

            Date time1 = cal.getTime();
            repairMapper.upadtaEndTime2(repairApplyId,time1);
        }
    }

    @Override
    public void daily() {
        //查询订单未2
        List<Repair> repairs =repairMapper.selectTimeoutOrders("2");
        if (Objects.isNull(repairs)){
            return;
        }else {

            //获取获取订单
            List<Repair> RepairTimeout = new ArrayList<Repair>();

            for (Repair s : repairs) {

                if (!Objects.isNull(s.getRepairApplyEndDate())) {
                    if (s.getRepairApplyEndDate().getTime() < new Date().getTime()) {
                        RepairTimeout.add(s);
                    }

                } else if (!Objects.isNull(s.getRepairFinishedDate())) {
                    if (s.getRepairFinishedDate().getTime() < new Date().getTime()) {
                        RepairTimeout.add(s);
                    }

                } else {

                }
            }

        RepairTimeout.stream().forEach(s ->
        {
            try {
                java.lang.Thread.sleep(60000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (Objects.isNull(s.getRepairRemind())){
                EmployeeDto leadership = employeeMapper.getByEmplCode(s.getRepairLeadership());
                String url_phone = "http://192.168.1.110:8081";
                //短息发送
                String param_phone = "SmsServer.ashx?id=1&phone=" +
                        leadership.getRemark() + "&phone=18608608556&" +

                        "&content=用户:你好!订单号" + s.getRepairApplyId() + "请填写每日进度！申请人" + s.getRepairName()
                        + "申请类型:" + s.getRepairApplyType() + "申请详情:" + s.getRepairApplyDetail() + "申请人电话:" + s.getRepairApplyPhone();
                sendGet(url_phone, param_phone);
                    //电话
                Date date = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //获取token
                com.alibaba.fastjson.JSONObject body = new com.alibaba.fastjson.JSONObject();
                body.put("username","13477857785");
                body.put("apiKey","6a$@m?*j261@l!f");
                body.put("transactionId","10086202211141249");
                Map l =   (Map)com.alibaba.fastjson.JSONObject.parseObject(HttpUtil.doPost(HttpUtil.url + HttpUtil.token, body)).get("bean");

                //请求头
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", (String) l.get("token"));
                String format = simpleDateFormat.format(date);
                String code = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, 5)));
                //添加任务
                Tenant tenant = new Tenant();
                tenant.setTransactionId(1085+format+code);
                tenant.setTenantId("2023040310553681671");
                tenant.setProcessId(2023040415132105486L);
                tenant.setProcessName("维修超时提醒");
                tenant.setTaskName("枝江测试"+simpleDateFormat1.format(new Date()));
                tenant.setConcurrentNum(1);
                tenant.setOutCallNums("07174516097");
                tenant.setIsAllday(1);
                tenant.setForever(1);
                tenant.setRecallNum(2);
                tenant.setRecallTime(1);
                tenant.setPlanStime("2023-01-11");
                tenant.setPlanEtime("2025-01-11");
                tenant.setStartTime1("08:00:00");
                tenant.setEndTime1("12:00:00");
                tenant.setStartTime2("14:00:00");
                tenant.setEndTime2("17:30:00");
                //添加人员信息
                List<CalledInfo> calledInfos = new ArrayList<>();
                CalledInfo calledInfo = new CalledInfo();
                calledInfo.setPhone(leadership.getRemark());
                ArrayList<Variable> variables = new ArrayList<>();
                Variable variable = new Variable();
                variable.setKey("repairApplyPhone");
                variable.setValue(s.getRepairApplyPhone());
                Variable variable1 = new Variable();
                variable1.setKey("repairApplyDetail");
                variable1.setValue(s.getRepairApplyDetail());
                Variable variable2 = new Variable();
                variable2.setKey("repairApplyType");
                variable2.setValue(s.getRepairApplyType());
                Variable variable3 = new Variable();
                variable3.setKey("deptName");
                variable3.setValue(s.getRepairApplyDept());
                Variable variable4 = new Variable();
                variable4.setKey("employeeName");
                variable4.setValue(s.getRepairName());
                Variable variable5 = new Variable();
                variable5.setKey("repairapplyid");
                variable5.setValue(s.getRepairApplyId());
                tenant.setCalledInfo(calledInfos);
                tenant.setCreateBy("2023040310553681671");
                tenant.setCreateUser("枝江市人民医院");
            }

        });

        }

    }

    @Override
    public void morningClock() {
        sendPhone2();
    }

    @Override
    public void Clock() {
        c();
    }


    @Override
    public void mrtx() {
        dailyReminders();
    }


    @Override
    public List<Repair> allRepair(String endTime, String startTime, String repairState) {
        //查询全部订单
        List<Repair> repairs =  repairMapper.getAllByRepairState(endTime,startTime,repairState);

        repairs.stream().forEach(s->{
            if (!Objects.isNull(s)){

                System.out.println(s);
                if (s.getRepairState().equals("2")||s.getRepairState().equals("3")){

//
                    EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s.getRepairOperator());
//                    System.out.println(z);

                            if (!Objects.isNull(byEmplCode)){
                                s.setRepairOperator(byEmplCode.getEmplName());
                                s.setRepairPhone(byEmplCode.getRemark());
                            }


                }
            }
        });

//        repairs.stream().forEach(s->{
//            if (s.getRepairState().equals("3")){
//                if (!Objects.isNull(s.getRepairApplyEndDate()) && !Objects.isNull(s.getRepairEndDate())){
//                    if (s.getRepairApplyEndDate().getTime()>s.getRepairEndDate().getTime()){
//                        s.setRepairState("完成");
//                    }else {
//                        s.setRepairState("超时完成");
//                    }
//                }else if (!Objects.isNull(s.getRepairFinishedDate())&&!Objects.isNull(s.getRepairEndDate())){
//                    if (s.getRepairFinishedDate().getTime()>s.getRepairEndDate().getTime()){
//                        s.setRepairState("完成");
//                    }else {
//                        s.setRepairState("超时完成");
//                    }
//                }
//
//
//            }else if (s.getRepairState().equals("2")){
//                s.setRepairState("已接单，待完成");
//            }else {
//                s.setRepairState("待接单");
//            }
//            if (!StringUtils.isEmpty(s.getRepairApplyDept())){
//                ComDepartment byDeptCode = employeeMapper.getByDeptCode(s.getRepairApplyDept());
//                if (Objects.isNull(byDeptCode)){
//
//                }else{
//                    s.setRepairApplyDept((String) byDeptCode.getDeptName());
//                }
//
//            }
//            if (!StringUtils.isEmpty(s.getRepairOperator())){
//                EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s.getRepairOperator());
//                if (Objects.isNull(byEmplCode)){
//
//                }else{
//                    s.setRepairOperator(byEmplCode.getEmplName());
//                }
//
//            }
//        });
        return repairs;
    }

    @Override
    public List<Assign> assignAll(String endTime, String startTime, String repairState) {
        List<Assign> assigns =  repairMapper.selectAll(endTime,startTime,repairState);
        return assigns;
    }

    @Override
    public void sendOfficialAccount(String dept,String data) {
        //公众号推送
        for(int i=0;i<AllOpenId.length;i++){
            String openId=AllOpenId[i];
            //JSON格式的字符串替换
            JSONObject jsonObj = JSONObject.fromObject(data1);
            String ss = jsonObj.getString("touser");
            data1 = data1.replace(ss,openId);
            data1 = data1.replace("申请科室所在地点",dept);
            data1 =data1.replace("信息系统软硬件故障",data);
            SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy月MM号dd日HH时mm分ss秒");
            data1 = data1.replace("现在",simpleDateFormat3.format(new Date()));
            System.out.println(data1);
            //公众号推送消息
            sendTemplateMessage();
        }
    }

    @Autowired
    WorkFlowMapper workFlowMapper;
    //oa 工作流
    @Override
    public PageDto<WorkFlow> workFlowList(int page,int pageSize) {
        //软件及数据快速服务反馈处置单
        List<WorkFlow> workFlow1 = workFlowMapper.getFittings();
        //需求改进
        List<WorkFlow> workFlow2 = workFlowMapper.getDemand();
        //授权
        List<WorkFlow> workFlow3 =workFlowMapper.getAuthorization();
        workFlow1.addAll(workFlow2);
        workFlow1.addAll(workFlow3);


//          List<WorkFlow> workFlow =  workFlowMapper.getList();

        List<WorkFlow> collect = workFlow1.stream().skip((page - 1) * pageSize).limit(pageSize).collect(Collectors.toList());

        //总页数
        Integer integer = NumberUtils.totalPages(Long.valueOf(String.valueOf(workFlow1.size())), pageSize);
        PageDto<WorkFlow> workFlowPageDto = new PageDto<>();
        workFlowPageDto.setCount(workFlow1.size());
        workFlowPageDto.setList(collect);
        workFlowPageDto.setPages(integer);
        return workFlowPageDto;
    }

    @Override
    public List<RepariOrder> selectAllRepairOrderEnd(String repairApplyOperator, String stateOne, String stateTwo, String repairStateOne, String repairStateTwo) {
        List<RepariOrder> repariOrders = repairMapper.selectAllRepairOrder9(repairApplyOperator, stateOne, stateTwo, repairStateOne, repairStateTwo);
        repariOrders.stream().forEach(
                s->{
                    TImage tImage = repairMapper.selcetTImage(s.getRepairApplyId());
                    if (Objects.isNull(tImage)){

                    }else {

                        FileInputStream stream = null;
                        try {
                            stream = new FileInputStream(tImage.getCodeUrl());
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }

                        String image  = Base64.encode(stream);
                        s.setImage("data:image/jpg;base64,"+image);
                    }
                    if (StringUtils.isEmpty(s.getRepairLeadership())){

                    }else {

                        EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s.getRepairLeadership());
                        s.setRepairLeadership(byEmplCode.getEmplName());

                        ComDepartment byDeptCode = employeeMapper.getByDeptCode(s.getRepairLeadershipDept());
                        s.setRepairLeadershipDept(byDeptCode.getDeptName().toString());
                    }




                }
        );


        return repariOrders;
    }





    private String    name;
    @Override
    public void sendWorkFlow() throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //时间
      List<WorkFlow> workFlows =  workFlowMapper.getToDayWorkFlow(simpleDateFormat.format(new Date()));

        ArrayList<WorkFlow> workFlows1 = new ArrayList<>();
        //
        if (workFlows.size()>0){

            for (WorkFlow w : workFlows) {
                name = w.getRequestName();
                if (w.getWorkFlowId().equals("19521")){
                   WorkFlow w1 = workFlowMapper.getOne1(w);
                        w.setRequestName(w1.getRequestName());
                }
                else if (w.getWorkFlowId().equals("1031")){
                    WorkFlow w1 =    workFlowMapper.getOne2(w);
                    w.setRequestName(w1.getRequestName());
                }
                else if (w.getWorkFlowId().equals("32521")){
                    WorkFlow w1 =   workFlowMapper.getOne3(w);
                    w.setRequestName(w1.getRequestName());
                }else if (w.getWorkFlowId().equals("36521")){
                    WorkFlow w1 =   workFlowMapper.getOne4(w);
                    System.out.println(w1+"===============================");
                    w.setRequestName(w1.getRequestName());
                }


                w.setLastOperateDate(w.getLastOperateDate()+" "+w.getLastOperateTime());
                w.setDate(simpleDateFormat1.parse(w.getLastOperateDate()));
                //查
            //  Repair repair =   repairMapper.getOne(w);
                Repair repair =   repairMapper.getById(w);

              if (Objects.isNull(repair)){
                  Repair repair1 = new Repair();
                 // repair1.setRepairApplyId(String.valueOf(System.currentTimeMillis()));
                  repair1.setRepairApplyId(w.getRequestId());
                  repair1.setRepairApplyDept("1501");
                  repair1.setRepairApplyOperator("000512");
                  repair1.setRepairApplyType("OA");
                  repair1.setRepairApplyDetail(w.getRequestName());
                  repair1.setRepairState("1");
                  repair1.setRepairApplyDate(simpleDateFormat1.parse(w.getLastOperateDate()));
                  repair1.setRepairEvaluate(null);
                  repair1.setState("1");
                  repair1.setSuggestion(null);
                  repair1.setRepairApplyPhone("13477837799");
                  repair1.setRepairApplyDate(w.getDate());
                  repair1.setRepairFinishedDate(new Date(new Date().getTime()+60000*30));

                  //添加成功   放入
                  Integer insert = repairMapper.insert(repair1);
                  System.out.println(insert);
                  workFlows1.add(w);
                  //发短信

                  String url_phone="http://192.168.1.110:8081";
//            //短息发送
                  String param_phone="SmsServer.ashx?id=1&" +
                          "phone=18871742296&" +
                          "phone=18608608556&" +
                          "phone=13477837799&" +
                          "phone=13872497873&" +
                          "phone=15072562385&" +
                          "phone=15872485525&" +
                           "phone=16607228157&" +

                          "content=有新的维修申请可以接单:"+"李长春"+"||"+"信息科"+"||"+"OA"+"||"+name+"||"+"13477837799";

                  System.out.println(param_phone);
                  String s = sendGet(url_phone, param_phone);
                  System.out.println(s);
                  System.out.println("短信"+name);

                  //公众号推送
                  for(int i=0;i<AllOpenId.length;i++){
                      String openId=AllOpenId[i];
                      //JSON格式的字符串替换
                      JSONObject jsonObj = JSONObject.fromObject(data1);
                      String ss = jsonObj.getString("touser");

                      data1 = data1.replace(ss,openId);

                      data1 = data1.replace("申请科室所在地点","信息科");
                      data1 =data1.replace("信息系统软硬件故障",w.getRequestName());
                      System.out.println(w.getRequestNameHtmlNew());
                      SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy月MM号dd日HH时mm分ss秒");
                      data1 = data1.replace("现在",simpleDateFormat3.format(new Date()));

                      //公众号推送消息
                      sendTemplateMessage();
                  }


              }

            }

            //发语音

        }
    }


    @Resource
    SuppliesMapper suppliesMapper;
    @Override
    public List<Supplies> querySupplies(String supplies) {



        return suppliesMapper.get(supplies);
    }

    @Override
    @Transactional
    public void addSupplies(List<Supplies> supplies,String repairApplyId) {
        if (supplies.size()>0){
            for (Supplies supply : supplies) {
                System.out.println(supply);
                Supplies supplie = suppliesMapper.getOneSupplies(supply.getItemCode(),repairApplyId);
               if (Objects.isNull(supplie)){
                    supply.setSuppliesDate(new Date());
                    supply.setRepairApplyId(repairApplyId);
                    suppliesMapper.addList(supply);
                } else {

                   suppliesMapper.updateOneByCode(repairApplyId,supply.getItemCode(),supply.getCountPrice(),supply.getCountNumber());
               }

            }

        }

    }

    @Override
    public List<Supplies> relevancyOrders(String repairApplyId) {
        List<Supplies> supplies = suppliesMapper.relevancyOrdersList(repairApplyId);

        log.info(repairApplyId+"repairApplyId");
       return supplies;

    }

    @Override
    public void deleteSupplies(String repairApplyId, String itemCode) {
        Supplies oneSupplies = suppliesMapper.getOneSupplies(itemCode, repairApplyId);
        log.info(oneSupplies.toString());
        if (!Objects.isNull(oneSupplies)){
            suppliesMapper.deleteOne(repairApplyId,itemCode);
        }

    }

    private void dailyReminders() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy月MM号dd日HH时mm分ss秒");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        com.alibaba.fastjson.JSONObject body = new com.alibaba.fastjson.JSONObject();
        body.put("username","13477857785");
        body.put("apiKey","6a$@m?*j261@l!f");
        body.put("transactionId","10086202211141249");
        Map a =   (Map)com.alibaba.fastjson.JSONObject.parseObject(HttpUtil.doPost(HttpUtil.url + HttpUtil.token, body)).get("bean");
        //请求头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", (String)a.get("token"));
        String format = simpleDateFormat.format(date);
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, 5)));
        //添加任务
        Tenant tenant = new Tenant();
        tenant.setTransactionId(1085+format+code);
        tenant.setTenantId("2023040310553681671");
        tenant.setProcessId(2023041708334105630L);
        tenant.setProcessName("任务数量提醒");
        tenant.setTaskName("任务数量提醒"+simpleDateFormat1.format(new Date()));
        tenant.setConcurrentNum(10);
        tenant.setOutCallNums("07174516097");
        tenant.setIsAllday(1);
        tenant.setForever(1);
        tenant.setRecallNum(2);
        tenant.setRecallTime(1);
        tenant.setPlanStime("2022-01-11");
        tenant.setPlanEtime("2026-01-11");
        tenant.setStartTime1("08:00:00");
        tenant.setEndTime1("12:00:00");
        tenant.setStartTime2("13:00:00");
        tenant.setEndTime2("15:30:00");
        //添加人员信息
        List<CalledInfo> calledInfos = new ArrayList<>();
//z        CalledInfo calledInfo = new CalledInfo();
        //查询订单未2
        List<Repair> repairs =repairMapper.selectTimeoutOrders("2");
        List<DutyTable> dutyTables = repairMapper.selectXxkPaiban();
        ArrayList<String> c = new ArrayList<>();

        repairs.stream().forEach(
                s->{
                    EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s.getRepairOperator());
                    String sf = "";

    String email = s.getRepairApplyDept()+"，"+s.getRepairApplyDetail()+",接单人"+byEmplCode.getEmplName()+'，'+sf+"完成时间"+simpleDateFormat3.format(new Date())+"====";
              c.add(email);
                }
        );

//        String s1 = collect1.replaceAll(" ", "");

//        dutyTables.stream().forEach(
//                s->{
//                                        String url_phone="http://192.168.1.110:8081";
////                    for (int i = 0; i < collect1.length(); i+=) {
////                        s1.substring(i,i+200);
////                        String param_phone ="SmsServer.ashx?id=1&phone="+"16607228157"+"&content="+s1;
////                        String s2 = sendGet(url_phone,param_phone);
////                        System.out.println(s2);
////                    }
//
//                        String param_phone ="SmsServer.ashx?id=1&phone="+"16607228157"+"&content="+collect1;
//                    String s2 = sendGet(url_phone,param_phone);
//                    System.out.println(s2);
//                }
//
//
//        );


        //短信
        //ArrayList<String> list = new ArrayList<>();
        Map<String, List<Repair>> collect = repairs.stream().collect(Collectors.groupingBy(Repair::getRepairOperator));

        collect.forEach((s,v)->{
            ArrayList<Variable> variables = new ArrayList<>();
            //添加任务
            CalledInfo calledInfo = new CalledInfo();
            EmployeeDto byEmplCode = employeeMapper.getByEmplCode(s);
            calledInfo.setRemark(byEmplCode.getRemark());
            calledInfo.setContacts(byEmplCode.getEmplName());
            calledInfo.setPhone(byEmplCode.getRemark());

            Variable variable1 = new Variable();
            variable1.setKey("number");
            variable1.setValue(String.valueOf(collect.keySet().size()));
            variables.add(variable1);
            calledInfo.setVariable(variables);
            calledInfos.add(calledInfo);



        });
//        ArrayList<String> list = new ArrayList<>();
//        for (Repair repair1 : repairs) {
//            EmployeeDto byEmplCode = employeeMapper.getByEmplCode(repair1.getRepairOperator());
//            SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy月MM号dd日HH时mm分ss秒");
//            String sf = "";
//            if (repair1.getAppraise().equals("true")){
//                sf+="加急";
//            }
//
//            String email = "维修单"+repair1.getRepairApplyId()+",申请人"+repair1.getRepairName()+",申请科室"+repair1.getRepairApplyDept()+"，申请详情"+repair1.getRepairApplyType()+"，接单人"+byEmplCode.getEmplName()+"。";
//            list.add(email);
//
//        }

         int i =c.size();
        System.out.println(i);

        for (DutyTable dutyTable : dutyTables) {

            for(int j=0;j<i;j+=3){
                List<String> integers = c.subList(j, j + 3 > c.size() ? c.size() : j + 3);
                System.out.println(integers);

//             List<String> useridlist = idList.subList(j, j+HttpUtil.MAX_NUM>idList.size()?idList.size():j+HttpUtil.MAX_NUM);
//             List<String> strings = c.subList(j, j += 3 > i ? i : 3 );
//             System.out.println(c.subList());
                String param_phone ="SmsServer.ashx?id=1&phone="+dutyTable.getPhone()+"&content="+integers.stream().collect(Collectors.joining(""));
                String url_phone="http://192.168.1.110:8081";
                String s = param_phone.replaceAll(" ", "");
                String s1 = s.replaceAll("<", "-");
                String s3 = s1.replaceAll(">", "-");

                String s2 = sendGet(url_phone,s3);
                    System.out.println(param_phone);

                System.out.println(s2);

            }


        }


    }



    public  static void smsUtil(String phone,String content){
        String urlStr = "http://192.168.1.110:8081/SmsServer.ashx";
        //创建json对象作为requestBody
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject();
        jsonObject.put("phone",phone);
        jsonObject.put("content",content);
        System.out.println(JSONUtil.toJsonStr(jsonObject));
        // 添加请求头信息
        Map<String, String > heads = new HashMap<>();
        // 使用json发送请求，下面的是必须的
        heads.put("Content-Type", "application/json;charset=UTF-8");
        /**
         ** headerMap是添加的请求头，
         body是传入的参数，这里选择json，后端使用@RequestBody接收
         */
        HttpResponse response = HttpRequest.post(urlStr)
                .headerMap(heads, false)
                .body(String.valueOf("<request><id>1</id><phone>"+phone+"</phone><content>"+content+"</content></request>"))
                .timeout(5 * 60 * 1000)
                .execute();
    }

    private void c() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取token
        com.alibaba.fastjson.JSONObject body = new com.alibaba.fastjson.JSONObject();
        body.put("username","13477857785");
        body.put("apiKey","6a$@m?*j261@l!f");
        body.put("transactionId","10086202211141249");
        Map s =   (Map)com.alibaba.fastjson.JSONObject.parseObject(HttpUtil.doPost(HttpUtil.url + HttpUtil.token, body)).get("bean");
        //请求头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", (String) s.get("token"));
        String format = simpleDateFormat.format(date);
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, 5)));
        //添加任务
        Tenant tenant = new Tenant();
        tenant.setTransactionId(1085+format+code);
        tenant.setTenantId("2023040310553681671");
        tenant.setProcessId(2023041008263505576L);
        tenant.setProcessName("下班打开");
        tenant.setTaskName("下班打卡"+simpleDateFormat1.format(new Date()));
//        tenant.setConcurrentNum(1);
        tenant.setOutCallNums("07174516097");
        tenant.setIsAllday(0);
        tenant.setForever(0);
        tenant.setRecallNum(2);
        tenant.setRecallTime(1);
        tenant.setPlanStime("2023-01-11");
        tenant.setPlanEtime("2025-01-11");
        tenant.setStartTime1("7:50:00");
        tenant.setEndTime1("12:00:00");
        tenant.setStartTime2("14:00:00");
        tenant.setEndTime2("17:50:00");
        //添加人员信息
        List<CalledInfo> calledInfos = new ArrayList<>();

        List<EmployeeDto> x = employeeMapper.findX2();
        //特殊人员提醒
//        EmployeeDto byEmplCode = employeeMapper.getByEmplCode("000367");
//        x.add(byEmplCode);
        tenant.setConcurrentNum(1);
        List<Switch> all = addressMapper.getAll();
//        Switch aSwitch = new Switch();
//        aSwitch.setPhone(byEmplCode.getRemark());
//        aSwitch.setName(byEmplCode.getEmplName());
//        all.add(aSwitch);
        //添加人员信息
        for (Switch aSwitch1 : all) {

             CalledInfo calledInfo = new CalledInfo();
            calledInfo.setRemark(aSwitch1.getPhone());
            calledInfo.setPhone(aSwitch1.getPhone());
            calledInfo.setContacts(aSwitch1.getName());
            calledInfos.add(calledInfo);
        }
//        for (EmployeeDto employeeDto : x) {
//            CalledInfo calledInfo = new CalledInfo();
//            calledInfo.setRemark(employeeDto.getRemark());
//            calledInfo.setPhone(employeeDto.getRemark());
//            calledInfo.setContacts(employeeDto.getEmplName());
//            calledInfos.add(calledInfo);
//        }
        tenant.setCalledInfo(calledInfos);
        String s1 = HttpUtil.doPostJson(HttpUtil.url + HttpUtil.Task, headers, com.alibaba.fastjson.JSONObject.toJSONString(tenant));

    }

    @Autowired
    AddressMapper addressMapper;
    private void sendPhone2() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取token
        com.alibaba.fastjson.JSONObject body = new com.alibaba.fastjson.JSONObject();
        body.put("username","13477857785");
        body.put("apiKey","6a$@m?*j261@l!f");
        body.put("transactionId","10086202211141249");
        Map s =   (Map)com.alibaba.fastjson.JSONObject.parseObject(HttpUtil.doPost(HttpUtil.url + HttpUtil.token, body)).get("bean");
        //请求头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", (String) s.get("token"));
        String format = simpleDateFormat.format(date);
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, 5)));
        //添加任务
        Tenant tenant = new Tenant();
        tenant.setTransactionId(1085+format+code);
        tenant.setTenantId("2023040310553681671");
        tenant.setProcessId(2023041008151105575L);
        tenant.setProcessName("早上打卡");
        tenant.setTaskName("早上打卡"+simpleDateFormat1.format(new Date()));

        tenant.setOutCallNums("07174516097");
        tenant.setIsAllday(0);
        tenant.setForever(0);
        tenant.setRecallNum(2);
        tenant.setRecallTime(1);

        tenant.setStartTime1("2:50:00");
        tenant.setEndTime1("4:00:00");
        tenant.setStartTime2("7:00:00");
        tenant.setEndTime2("9:50:00");
      //  EmployeeDto byEmplCode = employeeMapper.getByEmplCode("000367");

        List<EmployeeDto> x = employeeMapper.findX2();
        //
        List<Switch> all = addressMapper.getAll();
       // Switch aSwitch = new Switch();
      //  aSwitch.setPhone(byEmplCode.getRemark());
       // aSwitch.setName(byEmplCode.getEmplName());
      //  all.add(aSwitch);
        //添加人员信息
        List<CalledInfo> calledInfos = new ArrayList<>();
        for (Switch aSwitch1 : all) {

            CalledInfo calledInfo = new CalledInfo();
            calledInfo.setRemark(aSwitch1.getPhone());
            calledInfo.setPhone(aSwitch1.getPhone());
            calledInfo.setContacts(aSwitch1.getName());
            calledInfos.add(calledInfo);
        }

        //特殊人员提醒
//        EmployeeDto byEmplCode = employeeMapper.getByEmplCode("000367");
      //  x.add(byEmplCode);
        tenant.setConcurrentNum(1);
//        for (EmployeeDto employeeDto : x) {
//            CalledInfo calledInfo = new CalledInfo();
//            calledInfo.setRemark(employeeDto.getRemark());
//            calledInfo.setPhone(employeeDto.getRemark());
//            calledInfo.setContacts(employeeDto.getEmplName());
//            calledInfos.add(calledInfo);
//        }
        tenant.setPlanStime("2023-01-11");
        tenant.setPlanEtime("2025-05-11");
//        tenant.setStartTime1("1:40:00");
//        tenant.setEndTime1("2:00:00");
//        tenant.setStartTime2("16:00:00");
//        tenant.setEndTime2("18:30:00");
        tenant.setCalledInfo(calledInfos);
        System.out.println(JSONUtil.formatJsonStr(tenant.toString()));
        String s1 = HttpUtil.doPostJson(HttpUtil.url + HttpUtil.Task, headers, com.alibaba.fastjson.JSONObject.toJSONString(tenant));
        System.out.println(s1);

    }


    @Override
    public Integer updateAcceptState(String repairApplyId, String repairOperator, Date repairFinishedDate) {
        Repair repair = selectMyRepairOrderById(repairApplyId,"2");
        Integer state;
        repairFinishedDate=new Date();
        if (repair!=null&&repair.getRepairApplyId().equals(repairApplyId)){
            repairMapper.updateAcceptState(repairApplyId,repairOperator,repairFinishedDate);
            state=1;
        }else {
            state=-1;
        }
        return state;
    }

    @Override
    public List<DutyTable> selectXxkPaiban() {

        List<DutyTable> dutyTables = repairMapper.selectXxkPaiban();

        for (DutyTable dutyTable : dutyTables) {
            if (!StringUtils.isEmpty(dutyTable.getPhone())){
                DutyTable z = repairMapper.getZ(dutyTable.getEmplCode());
            if (!Objects.isNull(z)){
                 dutyTable.setBzmc(z.getBzmc());
                }
            }else {
                dutyTable.setBzmc("白");
            }
        }

        return dutyTables;
    }

    //会议签到20211005
    @Override
    public void meetingRecode(MeetingCheckRecode meetingCheckRecode) {
//        meetingCheckRecode.setEmpEndDate(new Date());
        //meetingCheckRecode.setEmpRemark2("1");
        //meetingCheckRecode.setEmpRemark3("1");
        meetingCheckRecode.setEmpMeetingvalid("1");
        meetingCheckRecode.setEmpBeginDate(new Date());
        meetingCheckRecode.setEmpReport("0");
        meetingCheckRecode.setEmpLeave("0");
        meetingCheckRecode.setEmpReplace("2");
        Integer row = repairMapper.insertMeeting(meetingCheckRecode);
        if (row != 1) {
            throw new InsertException("插入数据失败");
        }
    }

    @Override
    public List<MeetingCheckRecode> meetingSelect(String empCode,String meetingCode) {
        return repairMapper.meetingSelect(empCode,meetingCode);
    }

    @Override
    public Integer updateMeetingRecode(Date empBeginDate, String empCode,String meetingCode) {
        List<MeetingCheckRecode> meetingCheckRecodes = repairMapper.meetingSelect(empCode, meetingCode);
        Integer state=0;
        if (meetingCheckRecodes.size()>=1 && meetingCheckRecodes.get(0).getEmpBeginDate() == null&& meetingCheckRecodes.get(0).getMeetingCode().equals(meetingCode)&&meetingCheckRecodes.get(0).getEmpCode().equals(empCode)){
            empBeginDate=new Date();
            repairMapper.updateMeetingRecode(empBeginDate,empCode,meetingCode);
            state=1;
        }else if (meetingCheckRecodes.size()==0){
            MeetingCheckRecode meetingCheckRecode=new MeetingCheckRecode();
            meetingCheckRecode.setMeetingCode(meetingCode);
            meetingCheckRecode.setEmpCode(empCode);
            meetingCheckRecode.setEmpBeginDate(new Date());
            meetingCheckRecode.setEmpMeetingvalid("1");
            meetingCheckRecode.setEmpBeginDate(new Date());
            meetingCheckRecode.setEmpReport("0");
            meetingCheckRecode.setEmpLeave("0");
            meetingCheckRecode.setEmpReplace("2");

            List<Employee> employees = repairMapper.selectEmployeeByCode(empCode);
            meetingCheckRecode.setEmpName(employees.get(0).getEmployeeName());
            meetingCheckRecode.setEmpDeptCode(employees.get(0).getEmployeeDept());
            meetingCheckRecode.setEmpDeptName(employees.get(0).getEmployeeDeptName());
            meetingCheckRecode.setEmpPhone(employees.get(0).getIphone());

            List<MeetingCheckRecode> meetingCheckRecodes1 = repairMapper.meetingSelectById(meetingCode);
            if (meetingCheckRecodes1.size()>0)
            {
                meetingCheckRecode.setMeetingName(meetingCheckRecodes1.get(0).getMeetingName());
                meetingCheckRecode.setMeetingBeginDate(meetingCheckRecodes1.get(0).getMeetingBeginDate());
            }

            repairMapper.insertMeeting(meetingCheckRecode);
            state=2;
        }
        return state;
    }

    @Override
    public List<Employee> selectEmployeeByCode(String employeeId) {
        return repairMapper.selectEmployeeByCode(employeeId);
    }

    @Override
    public List<MeetingCheckRecode> meetingSelectById(String meetingCode) {
        return repairMapper.meetingSelectById(meetingCode);
    }

    @Override
    public Integer updatePersonRecode(String reportState, String leaveState, String replaceState, String empCode, String meetingCode) {
        List<MeetingCheckRecode> meetingCheckRecodes = repairMapper.meetingSelect(empCode, meetingCode);
        Integer num=0;
        if (meetingCheckRecodes.size()>0){
            repairMapper.updatePersonRecode(reportState,leaveState,replaceState,empCode,meetingCode);
            return num=1;
        }else {
            return num=-1;
        }
    }

    @Override
    public List<RepariOrder> selectAllRepairOrder2(String repairApplyOperator, String stateOne, String stateTwo, String repairStateOne, String repairStateTwo) {
        return repairMapper.selectAllRepairOrder2(repairApplyOperator,stateOne,stateTwo,repairStateOne,repairStateTwo);
    }

    @Override
    public void byRepairApplyIdSuggestion(String repairApplyId, String suggestion, String repairEvaluate) {
        if (!StringUtils.isEmpty(suggestion)||!StringUtils.isEmpty(repairEvaluate)){
            Repair repair = repairMapper.selectMyRepair(repairApplyId);
            if (StringUtils.isBlank(repair.getSuggestion())&&StringUtils.isBlank(repair.getRepairEvaluate())){
                repairMapper.updateSuggestion(repairApplyId,suggestion,repairEvaluate);
            }else {
                throw new RuntimeException("已评价");
            }

        }else {
            throw new RuntimeException("请填写评价或评分");
        }



    }

    @Override
    public List<Repair> selectByToDateRepairAll(String start, String end) {

        return repairMapper.selectByToDateRepairAll(start,end);
    }

    @Autowired
    EmployeeMapper employeeMapper;


    @Override
    public void lockout(String emplCode) {
        Date start = new Date();start.setHours(0);start.setMinutes(0); start.setSeconds(0);
        Date end = new Date();end.setHours(23);end.setMinutes(59); end.setSeconds(59);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<Repair> repairLockout  =  repairMapper.selectByToDateRepairLockout(emplCode,sdf.format(start),sdf.format(end));
            if (repairLockout.size()< 1) {
                String maxId = repairMapper.repairSelectMaxId();
                if (StrUtil.isNotBlank(maxId)) {
                    String day_base = maxId.substring(0, 8);
                    String currDate = DateUtil.format(DateUtil.date(), "yyyyMMdd");
                    if (day_base.equals(currDate)) {
                        String sequese_base = StrUtil.subSuf(maxId, 8);
                        Integer integer = Integer.valueOf(sequese_base) + 1;
                        String id = String.format("%4d", integer).replace(" ", "0");
                        maxId = day_base + id;
                    } else {
                        maxId = DateUtil.format(DateUtil.date(), "yyyyMMdd") + "0001";
                    }
                } else {
                    maxId = DateUtil.format(DateUtil.date(), "yyyyMMdd") + "0001";
                }
                Repair repair = new Repair();
                repair.setRepairApplyId(maxId);
                EmployeeDto employee = employeeMapper.getByEmplCode(emplCode);

                if (!employee.getDeptCode().equals("1501")) {
                    throw new RuntimeException("不是信息科人员不能停工");
                }

                repair.setRepairApplyDept("1501");
                repair.setRepairApplyOperator(emplCode);
                repair.setRepairApplyType("停工");
                repair.setRepairApplyDetail("停工");
                repair.setState("2");
                repair.setRepairState("4"); //停工
                repair.setRepairApplyDate(new Date());
                repair.setAppraise("false");
                repair.setRepairApplyPhone(employee.getRemark());
                repairMapper.insert1(repair);
            }else {
                throw new RuntimeException("今日已停工");
            }
    }

    @Override
    @Transactional
    public void dispatch(String emplCode, String emplName,String repairApplyId) {
        Repair repair = repairMapper.selectMyRepairOrderById(repairApplyId, "1");

        Date start = new Date();start.setHours(0);start.setMinutes(0); start.setSeconds(0);
        Date end = new Date();end.setHours(23);end.setMinutes(59); end.setSeconds(59);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      //  List<Repair> repairLockout  =  repairMapper.selectByToDateRepairLockout(emplCode,sdf.format(start),sdf.format(end));
        //判断是否是emplCode值
        EmployeeDto byEmplCode = employeeMapper.getByEmplCode(emplCode);
        ComDepartment byDeptCode = employeeMapper.getByDeptCode(repair.getRepairApplyDept());
        if (Objects.isNull(byEmplCode)){
    throw new RuntimeException("不是信息科人员不能派单");
}
//        List<DutyTable> dutyTables = repairMapper.selectXxkPaiban1();

        repairMapper.updateByRepairapplyid(repairApplyId,byEmplCode.getEmplCode(),new Date());
        repairMapper.addAssign(repairApplyId,emplName,new Date(),emplCode,"2");
        EmployeeDto byEmplCode1 = employeeMapper.getByEmplCode(emplCode);
//        dutyTables.stream().forEach(s->{
//            if (byEmplCode.getEmplName().equals(s.getEmplName())){
//
//
//                if (!s.equals("值")||!s.equals("休")){
//
//                    throw new RuntimeException("只有值班人员和休息人员才能派单");
//                }else {
//                    if (emplName.equals(s.getEmplName())){
//                        EmployeeDto employeesByPhone = employeeMapper.findEmployeesByPhone(s.getPhone());
//
//                            List<Repair> repairLockout  =  repairMapper.selectByToDateRepairLockout(employeesByPhone.getEmplCode(),sdf.format(start),sdf.format(end));
//                            if (repairLockout.size() > 0){
//
//                                throw new RuntimeException("已停工");
//                            }
//                            repairMapper.updateByRepairapplyid(repairApplyId,employeesByPhone.getEmplCode(),new Date());
//                            ComDepartment byDeptCode = employeeMapper.getByDeptCode(repair.getRepairApplyDept());
//            //短息发送
//        String url_phone="http://192.168.1.110:8081";
//        String param_phone="SmsServer.ashx?id=1&" +
//                "phone=18871742296&" +
//                "phone=18608608556&" +
//                "phone=13477837799&" +
//                "phone=13872497873&" +
//                "phone=15072562385&" +
//                "phone=15872485525&" +
//                "phone=18064244115&" +
//                "content=:"+byEmplCode1.getEmplName()+"已派单||请前往"+byDeptCode.getDeptName()+"||"+repair.getRepairApplyType()+"||"+repair.getRepairApplyDetail()+"||申请人手机号:"+repair.getRepairApplyPhone();
//        sendGet(url_phone,param_phone);
//
//                }
//
//            }
//
//
//            }
//
//        });


    }

    @Override
    public void appraise(String emplCode, String repairApplyId, String repairEvaluate, String suggestion) {
        repairMapper.updateSuggestion(repairApplyId,suggestion,repairEvaluate);


    }

    @Autowired
    ProgressMapper progressMapper;
    @Override
    public Repair progress(String repairApplyId, String progress) {
                Repair repair =repairMapper.selectMyRepair(repairApplyId);
        repairMapper.updateProgress(repairApplyId,progress);
        String i = "";
        if (repair.getRepairState().equals("2")){
            i=i+"未完成";
        }else if (repair.getRepairState().equals("3")){
            i=i+"已完成";
        }
        //  每天新增进度
        progressMapper.addProgress(repairApplyId,progress,new Date(),i);
        return null;
    }



    @Override
    public void automaticDispatch(List<Repair> repairs, String start, String end) {



        ArrayList<EmployeeDto> employeeDtos = new ArrayList<>();
        List<DutyTable> dutyTables = repairMapper.selectXxkPaiban1();
        //获取所有员工
        for (DutyTable dutyTable : dutyTables) {
           EmployeeDto employeesByPhone = employeeMapper.findEmployeesByPhone(dutyTable.getPhone());
            employeeDtos.add(employeesByPhone);
        }
        for (EmployeeDto employeeDto : employeeDtos) {
            String weixiu = stringRedisTemplate.opsForList().leftPop("weixiu");
            Repair repair = JSONUtil.toBean(weixiu, Repair.class);
            if (StringUtils.isBlank(repair.getRepairApplyId())){
                log.info("不存在任务");
            }else {
                repairMapper.updateByRepairapplyid(repair.getRepairApplyId(),employeeDto.getEmplCode(),new Date());
                String url_phone="http://192.168.1.110:8081";
                //            //短息发送
                String param_phone="SmsServer.ashx?id=1&" +
                        "phone=" +employeeDto.getRemark()+
                        "&content=当前有新的订单已自动分派给您:"+employeeDto.getEmplName()+"||"+employeeDto.getDeptName()+"||"+repair.getRepairApplyType()
                        +"||"+repair.getRepairApplyDetail()+"||"+repair.getRepairApplyPhone();
                sendGet(url_phone,param_phone);

            }



        }
        stringRedisTemplate.delete("weixiu");

            }

    @Override
    public List<Progress> selcetProgress(String repairApplyId) {
        //查询相关维修记录
        List<Progress> progresses = progressMapper.selcetAll(repairApplyId);
        return progresses;
    }

    @Override
    public List<Repair> getWeRepair(String repairApplyOperator) {
        List<Repair> repairs = repairMapper.getWeRepairByRepairApplyOperator(repairApplyOperator);
        return repairs;
    }

    @Override
    public Repair selectRepairById(String repairApplyId) {
        Repair repair = repairMapper.selectMyRepair(repairApplyId);
        return repair;
    }

    @Override
    public void designateRepair(String repairApplyId, String employeeId) {
        //判断是否是值班人员

        //指派其他人


    }
    @Value("${file.upload.url}")
    private String uploadFilePath;

    @Override
    public void uploadImg(MultipartFile files, String repairApplyId) throws IOException {





                // 获取上传文件的原始文件名
                String originalFilename = files.getOriginalFilename();
//        // 获取原始文件名的后缀
//        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                // 使用UUID重新生成文件名，防止文件名称重复造成文件覆盖    会议号+文件名
                String fileName =repairApplyId + originalFilename;


                // 创建一个目录对象
                File dir = new File("/");
                // 判断当前目录是否存在
                if (!dir.exists()) {
                    // 目录不存在，需要创建
                    dir.mkdirs();
                }
                Repair repair = repairMapper.selectMyRepair(repairApplyId);

                TImage tImage = new TImage();
                tImage.setCodeUrl(uploadFilePath + fileName);
                tImage.setCreatrTime(new Date());
                tImage.setRepairApplyId(repairApplyId);
                tImage.setCode(UUID.randomUUID().toString());

                repairMapper.upLaod(tImage);

                try {
                    // file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会被删除
                    // basePath 是指定的保存路径，我们在上面声明了一个属性，属性值从yml配置文件读取，以便修改
                    // 这里可能会有IO异常，我们需要把它抛出去
                    files.transferTo(new File(uploadFilePath + fileName));

                } catch (IOException e) {
                    e.printStackTrace();
                }






    }

    @Override
    public String imgPreview(String repairApplyId) throws FileNotFoundException {
     //   String url = "data:image/jpg;base64,";
        TImage tImage = repairMapper.selcetTImage(repairApplyId);


        if (Objects.isNull(tImage)){
            return null;
        }
        // path是指欲下载的文件的路径。
        File file = new File(tImage.getCodeUrl());
        // 取得文件名。
        String filename = file.getName();
        // 取得文件的后缀名。
        String ext = filename.substring(".".lastIndexOf(filename) + 1).toUpperCase();

        FileInputStream stream = new FileInputStream(tImage.getCodeUrl());

        String image  = Base64.encode(stream);
            return image;
    }

    @Override
    public List<RepariOrder> selectAllRepairOrder8(String repairApplyOperator, String stateOne, String stateTwo, String repairStateOne, String repairStateTwo) {
        return null;
    }

}


